from rest_framework.response import Response

from apps.minapp.models import User, Window
from rest_framework.mixins import ListModelMixin, RetrieveModelMixin
from rest_framework.pagination import PageNumberPagination
from rest_framework.viewsets import GenericViewSet
from rest_framework import serializers
from django_filters.rest_framework import DjangoFilterBackend, FilterSet, CharFilter
from rest_framework.filters import OrderingFilter, SearchFilter


class UserSerializer(serializers.ModelSerializer):
    gender = serializers.SerializerMethodField()

    class Meta:
        model = User
        exclude = ['openid', 'session_key', 'token', 'password', 'avatar']

    def get_gender(self, obj):
        return obj.get_gender_display()


class UserPagination(PageNumberPagination):
    page_size = 5
    page_query_param = 'pageNum'
    page_size_query_param = 'pageSize'
    max_page_size = 20


class UserView(ListModelMixin, RetrieveModelMixin, GenericViewSet):
    authentication_classes = []
    queryset = User.objects.all().filter(disabled=False).order_by('id')
    filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter]
    serializer_class = UserSerializer
    search_fields = ['studentid', 'name', 'role', 'gender']
    pagination_class = UserPagination

    def create(self, request, *args, **kwargs):
        newuser_data = request.data
        newuser = User.objects.create(**newuser_data)
        newuser.save()
        return Response({"error_num": 0})

    def update(self, request, *args, **kwargs):
        user_id = kwargs['pk']
        user_data = request.data
        try:
            user = User.objects.get(id=user_id)
            user.__dict__.update(**user_data)
            user.save()
        except Exception as e:
            print(e)
        return Response({'error_num': 0})

    def delete(self, request, *args, **kwargs):
        user_id = kwargs['pk']
        try:
            user = User.objects.get(id=user_id)
            user.disabled = True
            user.save()
        except Exception as e:
            print(e)
        return Response({'error_num': 0})
